#HOST = '10.10.17.163'
HOST = '127.0.0.1'
import os
from django.conf import settings
from my.settings import DATABASES
settings.configure(DATABASES=DATABASES)
import time
import beanstalkc

from my.m import myjob
from my.m.models import Video, Status, Shot

#import encode
#import thumb

DIR_BASE = '/t'

def _get_v(nid_video):
    v = Video.objects.filter(id = nid_video)[0]
    return v

def do_transcode(nid_video):
    v = _get_v(nid_video)
    v.status_transcode = Status.DOING
    #v = Video()
    szsrc = v.src
    szdst = 'out/%(nid_video)s/video/0.mp4' % dict(nid_video=nid_video,)
    v.dst = szdst
    v.save()
    szsrc_full = os.path.join(DIR_BASE,szsrc)
    szdst_full = os.path.join(DIR_BASE,szdst)
    from mymedia import encode
    encode.encode(szsrc_full,szdst_full)
    #encode(szsrc_full,szdst_full)
    
    print 'do_transcode',nid_video
    print szsrc_full
    print szdst_full 
    #time.sleep(5)

    v = _get_v(nid_video)
    v.status_transcode = Status.DONE
    v.save()
    
def do_catalog(nid_video):
    print 'do_catalog',nid_video
    v = _get_v(nid_video)
    #v = Video()
    v.status_catalog = Status.DOING
    v.save()
    
    #time.sleep(5)
    from mymedia import thumb
    
    szdir_base = DIR_BASE
    szsrc = v.dst
    szdir_thumb = 'out/%(nid_video)s/thumb' % dict(nid_video=nid_video,)
    nthumb_max = 100    
    
    print 'START CATALOG with=', szdir_base, szsrc, szdir_thumb, nthumb_max
    
    l_thumb = thumb.get(szdir_base, szsrc, szdir_thumb, nthumb_max)
    
    v = _get_v(nid_video)
    v.shot_set.add(*[Shot(nsec=i.nsec,path=i.szpath) for i in l_thumb])
    v.status_catalog = Status.DONE
    v.save()
   
def main():    
    
    while 1:
        try:
            c = beanstalkc.Connection(host=HOST)
            c.watch(myjob.Transcode.sztube)
            c.watch(myjob.Catalog.sztube)
            while 1:
                j = c.reserve(timeout=None)
                szbody = j.body
                j.bury()
    
                d_stat = j.stats()
                sztube = d_stat['tube']     
                
                if sztube == myjob.Transcode.sztube:
                    t = myjob.Transcode.load(szbody)
                    do_transcode(t.videoid)
                    
                    print 'PUTTING CATALOG'
                    #if success put to catalog
                    c.use(myjob.Catalog.sztube)
                    c.put(myjob.Catalog(videoid=t.videoid).dump())
                    
                elif sztube == myjob.Catalog.sztube:
                    t = myjob.Catalog.load(szbody)
                    do_catalog(t.videoid)
                j.delete()
        except:
            time.sleep(3)
            import traceback
            traceback.print_exc()                    
        finally:
            if c:
                c.close()                    
            

            
if __name__ == '__main__':
    main()
            